package cn.org.dian.easycommunicate.model;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.util.Log;
import cn.org.dian.easycommunicate.xml.XmlParser;

/**
 * Data entry for the whole app.
 * Should call {@link #init(InputStream)} before using it.
 * @author LiuGen
 * @date 2011-1-21
 * @see #init(InputStream)
 *
 */
public class DataCenter {
    
    public static boolean hasNotifiedTTSNotSupport = false;
    
    private static final String TAG = "DataCenter";
    
    private static Content content = null;
    
    private static List<String> allTermNames = new ArrayList<String>();
    
    /**
     * Use a xml file to init
     * @param is InputStream for the content.xml
     * @return true if successes, false if any problem occurs
     */
    public static boolean init(InputStream is) {
        if (null != content) {
            return true;
        }
        
        if (null != is) {
            Log.d(TAG, "load xml success");
            content = XmlParser.readContentfromXML(is);
//           Log.d(TAG, content.toString());
            if (null != content) {
                return true;
            } else {
                return false;
            }
        } else {
            Log.d(TAG, "load xml fail");
            return false;
        }
    }
    private DataCenter() {

    }
    
    public static String[] getAllSupportLanguages() {

        return Term.getAllLanguageNames().toArray(new String[0]);
    }
    
    public static String[] getAllThemeName() {
        return Theme.getAllThemeNames().toArray(new String[0]);
    }
    
    public static Theme getTheme(int themeIndicator) {
        String themeName = Theme.getAllThemeNames().get(themeIndicator);
        return content.getAllThemes().get(themeName);
    }
    
    /**
     * this method is used for the search service
     * @param query key word for query
     * @return a list of term names that contain the key word
     */
    public static List<String> searchTerm(String query) {
        List<String> resultList = new ArrayList<String>();

        for (String termName : allTermNames) {
            if (termName.contains(query)) {
                resultList.add(termName);
            }
        }
                
        return resultList;
    }
    
    public static void addAllTermName(String termName) {
        allTermNames.add(termName);
    }
    
    public static Term getTerm(String termName) {
        HashMap<String, Theme> allTheme = content.getAllThemes();
        
        for (String themeName : content.getAllThemes().keySet()) {
            if (allTheme.get(themeName).getAllTermsUnderTheme().containsKey(termName)) {
                return allTheme.get(themeName).getAllTermsUnderTheme().get(termName);
            }
        }
        return null;
    }
}
